home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / prolog / modprolg / mod-prol.lha / Prolog / modlib / src / $setof.P < prev    next >
Encoding:
Text File  |  1992-05-27  |  15.2 KB  |  424 lines

  1. /* $setof.P */
  2.  
  3. %   File   : SETOF.PL
  4. %   Author : R.A.O'Keefe
  5. %   Updated: 17 November 1983
  6. %   Purpose: define set_of/3, bag_of/3, findall/3, and findall/4
  7. %   Needs  : Not.Pl
  8. %
  9. %   Modified for SB-Prolog by Saumya K. Debray, May 1988.
  10. %   Some of the code for the SB-Prolog version, specifically
  11. %   the version of $findall/3 using buff_code, was written by
  12. %   David S. Warren (in 1986?).
  13.  
  14. /*  This file defines two predicates which act like setof/3 and bagof/3.
  15.     I have seen the code for these routines in Dec-10 and in C-Prolog,
  16.     but I no longer recall it, and this code was independently derived
  17.     in 1982 by me and me alone.
  18.  
  19.     Most of the complication comes from trying to cope with free variables
  20.     in the Filter; these definitions actually enumerate all the solutions,
  21.     then group together those with the same bindings for the free variables.
  22.     There must be a better way of doing this.  I do not claim any virtue for
  23.     this code other than the virtue of working.  In fact there is a subtle
  24.     bug: if setof/bagof occurs as a data structure in the Generator it will
  25.     be mistaken for a call, and free variables treated wrongly.  Given the
  26.     current nature of Prolog, there is no way of telling a call from a data
  27.     structure, and since nested calls are FAR more likely than use as a
  28.     data structure, we just put up with the latter being wrong.  The same
  29.     applies to negation.
  30.  
  31.     Would anyone incorporating this in their Prolog system please credit
  32.     both me and David Warren;  he thought up the definitions, and my
  33.     implementation may owe more to subconscious memory of his than I like
  34.     to think.  At least this ought to put a stop to fraudulent claims to
  35.     having bagof, by replacing them with genuine claims.
  36.  
  37.     Thanks to Dave Bowen for pointing out an amazingly obscure bug: if
  38.     the Template was a variable and the Generator never bound it at all
  39.     you got a very strange answer!  Now fixed, at a price.
  40. */
  41.  
  42. /****************************************************************************
  43.  *                                                                          *
  44.  * This file has been changed by to include Modules Extensions              *
  45.  * Changes by : Brian Paxton 1991/92                                        *
  46.  * Last update : June 1992                                                  *
  47.  *                                                                          *
  48.  * Organisation : University of Edinburgh.                                  *
  49.  * For : Departments of Computer Science and Artificial Intelligence        *
  50.  *       Fourth Year Project.                                               *
  51.  *                                                                          *
  52.  ****************************************************************************/
  53.  
  54. % I have simply tidied up this file, as much of the original was unused.
  55. % B Paxton
  56.  
  57. $setof_export([$setof/3,$bagof/3,$findall/3,$sort/2,$keysort/2,'^'/2]).
  58.  
  59. % $setof_use : $meta $buff $bmeta
  60.  
  61. %   findall(Template, Generator, List)
  62. %   is a special case of bagof, where all free variables in the
  63. %   generator are taken to be existentially quantified.  It is
  64. %   described in Clocksin & Mellish on p152.  The code they give
  65. %   has a bug (which the Dec-10 bagof and setof predicates share)
  66. %   which this has not.
  67.  
  68. % SB-Prolog doesn't have record/recorded, so we use buff_code.
  69.  
  70. % B Paxton - Actually it has, but they are pretty basic, and do not
  71. %            deallocate their space after items have been removed.
  72. %            Too many calls to findall, bagof or setof would fill the
  73. %            permanent program space!
  74.  
  75. $findall(T,Call,Result) :-
  76.     $alloc_heap(10000,Buff),
  77.     $findall_1(T,Call,Result,Buff).
  78.  
  79. $findall_1(T,Call,Result,Buff) :-
  80.     $copyterm([],Buff,8,4,_), /* init result list to empty */
  81.     $buff_code(Buff,0,2 /*pn*/ ,8), /* init where to put next answer */
  82.     $buff_code(Buff,4,2 /*pn*/ ,12), /* init first free place */
  83.     call(Call),
  84.     $buff_code(Buff,0,5 /*gn*/ ,Place), /* get where to put answer */
  85.     $buff_code(Buff,4,5 /*gn*/ ,Start), /* get first free place */
  86.     $copyterm([T],Buff,Place,Start,End),
  87.     Tailloc is Start+4,    
  88.     $buff_code(Buff,0,2 /*pn*/ ,Tailloc), /* where to put next answer */
  89.     $buff_code(Buff,4,2 /*pn*/ ,End), /* next first free place */
  90.     fail.
  91.  
  92. $findall_1(_,_,Result,Buff) :-
  93.     $buff_code(Buff,4,5 /*gn*/ ,Length), /* Length =\= 12 fail if [] */
  94.     $trimbuff(Length,Buff,1),
  95.     $buff_code(Buff,8,18 /*vtb*/ ,Result).
  96.  
  97.  
  98. %   $setof(Template, Generator, Set)
  99. %   finds the Set of instances of the Template satisfying the Generator.
  100. %   The set is in ascending order (see compare/3 for a definition of
  101. %   this order) without duplicates, and is non-empty.  If there are
  102. %   no solutions, set_of fails.  set_of may succeed more than one way,
  103. %   binding free variables in the Generator to different values.  This
  104. %   predicate is defined on p51 of the Dec-10 Prolog manual.
  105.  
  106. $setof(Template, Filter, Set) :-
  107.     $bagof(Template, Filter, Bag),
  108.     $sort(Bag, Set).
  109.  
  110.  
  111.  
  112. %   $bagof(Template, Generator, Bag)
  113. %   finds all the instances of the Template produced by the Generator,
  114. %   and returns them in the Bag in they order in which they were found.
  115. %   If the Generator contains free variables which are not bound in the
  116. %   Template, it assumes that this is like any other Prolog question
  117. %   and that you want bindings for those variables.  (You can tell it
  118. %   not to bother by using existential quantifiers.)
  119. %   bag_of records three things under the key '.':
  120. %    the end-of-bag marker           -
  121. %    terms with no free variables   -Term
  122. %    terms with free variables   Key-Term
  123. %   The key '.' was chosen on the grounds that most people are unlikely
  124. %   to realise that you can use it at all, another good key might be ''.
  125. %   The original data base is restored after this call, so that set_of
  126. %   and bag_of can be nested.  If the Generator smashes the data base
  127. %   you are asking for trouble and will probably get it.
  128. %   The second clause is basically just findall, which of course works in
  129. %   the common case when there are no free variables.
  130. %
  131. % SB-Prolog version modified to use findall instead of record/recorded - SKD
  132. %
  133.  
  134. $bagof(Template, Generator, Bag) :-
  135.     $free_variables(Generator, Template, [], Vars),
  136.     Vars \= [],
  137.     !,
  138.     Key =.. [.|Vars],
  139.     $functor(Key, ., N),
  140.         $findall(Key-Template,Generator,OmniumGatherum),
  141.     $keysort(OmniumGatherum, Gamut), !,
  142.     $concordant_subset(Gamut, Key, Answer),
  143.     Bag = Answer.
  144. $bagof(Template, Generator, Bag) :-
  145.         $findall(Template,Generator,Bag).
  146.  
  147. %   There is a bug in the compiled version of arg in Dec-10 Prolog,
  148. %   hence the rather strange code.  Only two calls on arg are needed
  149. %   in Dec-10 interpreted Prolog or C-Prolog.
  150.  
  151. $replace_key_variables(0, _, _) :- !.
  152. $replace_key_variables(N, OldKey, NewKey) :-
  153.     arg(N, NewKey, Arg),
  154.     nonvar(Arg), !,
  155.     M is N-1,
  156.     $replace_key_variables(M, OldKey, NewKey).
  157. $replace_key_variables(N, OldKey, NewKey) :-
  158.     arg(N, OldKey, OldVar),
  159.     arg(N, NewKey, OldVar),
  160.     M is N-1,
  161.     $replace_key_variables(M, OldKey, NewKey).
  162.  
  163.  
  164.  
  165. %   $concordant_subset([Key-Val list], Key, [Val list]).
  166. %   takes a list of Key-Val pairs which has been keysorted to bring
  167. %   all the identical keys together, and enumerates each different
  168. %   Key and the corresponding lists of values.
  169.  
  170. $concordant_subset([Key-Val|Rest], Clavis, Answer) :-
  171.     $concordant_subset(Rest, Key, List, More),
  172.     $concordant_subset(More, Key, [Val|List], Clavis, Answer).
  173.  
  174.  
  175. %   $concordant_subset(Rest, Key, List, More)
  176. %   strips off all the Key-Val pairs from the from of Rest,
  177. %   putting the Val elements into List, and returning the
  178. %   left-over pairs, if any, as More.
  179.  
  180. $concordant_subset([Key-Val|Rest], Clavis, [Val|List], More) :-
  181.     Key == Clavis,
  182.     !,
  183.     $concordant_subset(Rest, Clavis, List, More).
  184. $concordant_subset(More, _, [], More).
  185.  
  186.  
  187. %   $concordant_subset/5 tries the current subset, and if that
  188. %   doesn't work if backs up and tries the next subset.  The
  189. %   first clause is there to save a choice point when this is
  190. %   the last possible subset.
  191.  
  192. $concordant_subset([],   Key, Subset, Key, Subset) :- !.
  193. $concordant_subset(_,    Key, Subset, Key, Subset).
  194. $concordant_subset(More, _,   _,   Clavis, Answer) :-
  195.     $concordant_subset(More, Clavis, Answer).
  196.  
  197.  
  198. %   File   : NOT.PL
  199. %   Author : R.A.O'Keefe
  200. %   Updated: 17 November 1983
  201. %   Purpose: "suspicious" negation 
  202.  
  203. /*  This file defines a version of 'not' which checks that there are
  204.     no free variables in the goal it is given to "disprove".  Bound
  205.     variables introduced by the existential quantifier ^ or set/bag
  206.     dummy variables are accepted.  If any free variables are found, 
  207.     a message is printed on the terminal and a break level entered.
  208.  
  209.     It is intended purely as a debugging aid, though it shouldn't slow
  210.     interpreted code down much.  There are several other debugging
  211.     aids that you might want to use as well, particularly
  212.     unknown(_, trace)
  213.     which will detect calls to undefined predicates (as opposed to
  214.     predicates which have clauses that don't happen to match).
  215.  
  216.     The predicate $free_variables/4 defined in this files is also used
  217.     by the set_of/bag_of code.
  218.  
  219.     Note: in Dec-10 Prolog you should normally use "\+ Goal" instead
  220.     of "not(Goal)".  In C-Prolog you can use either, and would have to
  221.     do some surgery on pl/init to install this version of "not".  The
  222.     reason that I have called this predicate "not" is so that people
  223.     can choose whether to use the library predicate not/1 (in Invoca.Pl)
  224.     or this debugging one, not because I like the name.
  225. */
  226.  
  227.  
  228. %   In order to handle variables properly, we have to find all the 
  229. %   universally quantified variables in the Generator.  All variables
  230. %   as yet unbound are universally quantified, unless
  231. %    a)  they occur in the template
  232. %    b)  they are bound by X^P, setof, or bagof
  233. %   $free_variables(Generator, Template, OldList, NewList)
  234. %   finds this set, using OldList as an accumulator.
  235.  
  236. $free_variables(Term, Bound, VarList, [Term|VarList]) :-
  237.     var(Term),
  238.     $term_is_free_of(Bound, Term),
  239.     $list_is_free_of(VarList, Term),
  240.     !.
  241. $free_variables(Term,_Bound, VarList, VarList) :-
  242.     var(Term),
  243.     !.
  244. $free_variables(Term, Bound, OldList, NewList) :-
  245.     $explicit_binding(Term, Bound, NewTerm, NewBound),
  246.     !,
  247.     $free_variables(NewTerm, NewBound, OldList, NewList).
  248. $free_variables(Term, Bound, OldList, NewList) :-
  249.     $functor(Term, _, N),
  250.     $free_variables(N, Term, Bound, OldList, NewList).
  251.  
  252. $free_variables(0,_Term,_Bound, VarList, VarList) :- !.
  253. $free_variables(N, Term, Bound, OldList, NewList) :-
  254.     arg(N, Term, Argument),
  255.     $free_variables(Argument, Bound, OldList, MidList),
  256.     M is N-1, !,
  257.     $free_variables(M, Term, Bound, MidList, NewList).
  258.  
  259. %   $explicit_binding checks for goals known to existentially quantify
  260. %   one or more variables.  In particular \+ is quite common.
  261.  
  262. $explicit_binding(\+ _Goal,           Bound, fail,    Bound      ) :- !.
  263. $explicit_binding(not(_Goal),           Bound, fail,    Bound       ) :- !.
  264. $explicit_binding(Var^Goal,           Bound, Goal,    Bound+Var) :- !.
  265. $explicit_binding(setof(Var,Goal,Set),  Bound, Goal-Set, Bound+Var) :- !.
  266. $explicit_binding(bagof(Var,Goal,Bag),  Bound, Goal-Bag, Bound+Var) :- !.
  267. $explicit_binding(set_of(Var,Goal,Set), Bound, Goal-Set, Bound+Var) :- !.
  268. $explicit_binding(bag_of(Var,Goal,Bag), Bound, Goal-Bag, Bound+Var) :- !.
  269.  
  270.  
  271. $term_is_free_of(Term, Var) :-
  272.     var(Term), !,
  273.     Term \== Var.
  274. $term_is_free_of(Term, Var) :-
  275.     $functor(Term, _, N),
  276.     $term_is_free_of(N, Term, Var).
  277.  
  278. $term_is_free_of(0,_Term,_Var) :- !.
  279. $term_is_free_of(N, Term, Var) :-
  280.     arg(N, Term, Argument),
  281.     $term_is_free_of(Argument, Var),
  282.     M is N-1, !,
  283.     $term_is_free_of(M, Term, Var).
  284.  
  285.  
  286. $list_is_free_of([Head|Tail], Var) :-
  287.     Head \== Var,
  288.     !,
  289.     $list_is_free_of(Tail, Var).
  290. $list_is_free_of([], _).
  291.  
  292. /*======================================================================*/
  293.  
  294. /* This routine copies a term into a buffer. It is passed:
  295.     Term: the term to copy,
  296.     Buffer: the buffer to copy it into,
  297.     Worddisp: the word of the buffer in which to put the copy (or
  298.         a pointer to the copy.)
  299.     Start: the disp of the next free location in the buffer, before the 
  300.         copy is done.
  301.     End: (returned) the location of the first free location after the
  302.         copying.
  303.  
  304.     Variables are copied into the buffer and the copied variables are
  305.     pointed into the buffer and trailed. Thus later binding of these 
  306.     `outside' variables will cause the copied variables to be changed,
  307.     too. If, however, the $copyterm call is failed over, the variables
  308.     in the buffer will be ``disconnected'' from the outer variables.
  309.  
  310.     Copyterm is a prime candidate for moving down into the simulator as
  311.     a builtin written in C.
  312. */
  313.  
  314.  
  315. $copyterm(Term,Buff,Worddisp,Start,Start) :-
  316.     var(Term),!,$buff_code(Buff,Worddisp,17 /*pvar*/ ,Term).
  317.  
  318. $copyterm(Term,Buff,Worddisp,Start,Start) :-
  319.     number(Term),!,$buff_code(Buff,Worddisp,14 /*ptv*/ ,Term).
  320.  
  321. $copyterm(Term,Buff,Worddisp,Start,Start) :-
  322.     $atom(Term),!,$buff_code(Buff,Worddisp,14 /*ptv*/ ,Term).
  323.  
  324. $copyterm(Term,Buff,Worddisp,Start,End) :-
  325.     Term=[_|_],!,
  326.     $buff_code(Buff,Worddisp,16 /*ptl*/ ,Start), /* ptr to list rec */
  327.     Newstart is Start+8, /* reserve rec space */
  328.     $copyargs(Term,1,2,Buff,Start,Newstart,End).
  329.     
  330. $copyterm(Term,Buff,Worddisp,Start,End) :-
  331.     $structure(Term),!,
  332.     $buff_code(Buff,Worddisp,15 /*ptp*/ ,Start), /* ptr to str rec */
  333.     $buff_code(Buff,Start,0 /*ppsc*/ ,Term), /* rec psc ptr */
  334.     Argsloc is Start+4,
  335.     $arity(Term,Arity),Newstart is Argsloc+4*Arity, /* reserve rec space*/
  336.     $copyargs(Term,1,Arity,Buff,Argsloc,Newstart,End).
  337.     
  338. $copyargs(Term,Argno,Maxargs,Buff,Argloc,Start,End) :- 
  339.     Argno > Maxargs,
  340.      Start=End;
  341.     Argno =< Maxargs,
  342.      arg(Argno,Term,Arg),$copyterm(Arg,Buff,Argloc,Start,Mid),
  343.      Nargno is Argno+1, Nargloc is Argloc+4,
  344.      $copyargs(Term,Nargno,Maxargs,Buff,Nargloc,Mid,End).
  345.  
  346.  
  347. $sort(L,R) :- $length(L,N), $sort(N,L,_,R).
  348.  
  349. $sort(N,U,L,R) :-
  350.     N > 2 ->
  351.         (N1 is N >> 1, N2 is N-N1,
  352.          $sort(N1,U,L2,R1),
  353.          $sort(N2,L2,L,R2),
  354.          $merge(R1,R2,R)
  355.         ) ;
  356.         (N =:= 2 ->
  357.             (U = [X1|L1],
  358.              L1 = [X2|L],
  359.              compare(Delta,X1,X2),
  360.              (Delta ?= (<) -> R = [X1,X2] ;
  361.               Delta ?= (>) -> R = [X2,X1] ;
  362.                         R = [X2]
  363.              )
  364.             ) ;
  365.             (N =:= 1 ->
  366.                 (U = [X|L], R = [X]) ;
  367.                 (U = L, R = [])        /* N == 0 */
  368.             )
  369.          ).
  370.  
  371. $merge(R1,R2,R3) :-
  372.    R1 ?= [] ->
  373.        R3 = R2 ;
  374.    R2 ?= [] ->
  375.        R3 = R1 ;
  376.        (R1 = [X1|R1a], R2 = [X2|R2a], R3 = [X|R],
  377.         compare(Delta,X1,X2),
  378.         (Delta ?= (<) ->
  379.             (X = X1, $merge(R1a,R2,R)) ;
  380.             (Delta ?= (>) ->
  381.                 (X = X2, $merge(R1,R2a,R)) ;
  382.             (X = X1, $merge(R1a,R2a,R))
  383.             )
  384.     )
  385.        ).
  386.  
  387. /* Sorting on keys by bisecting and merging. */
  388.  
  389. $keysort(L,R) :- $length(L,N), $keysort(N,L,_,R1), R=R1.
  390.  
  391. $keysort(N,U,L,R) :-
  392.     N > 2 ->
  393.          (N1 is N >> 1, N2 is N-N1,
  394.           $keysort(N1,U,L2,R1),
  395.              $keysort(N2,L2,L,R2),
  396.              $keymerge(R1,R2,R)
  397.          ) ;
  398.         (N =:= 2 ->
  399.          (U = [X1|L1],
  400.           L1 = [X2|L],
  401.           $compare_keys(Delta,X1,X2),
  402.           (Delta ?= (>) -> R = [X2,X1] ; R = [X1,X2])
  403.          ) ;
  404.     (N =:= 1 ->
  405.          (U = [X|L], R = [X]) ;
  406.          (U = L, R = [])        /* N == 0 */
  407.          )).
  408.  
  409. $keymerge([],R,R) :- !.
  410. $keymerge(R,[],R) :- !.
  411. $keymerge(R1,R2,[X|R]) :-
  412.    R1 = [X1|R1a], R2 = [X2|R2a],
  413.    $compare_keys(Delta,X1,X2),
  414.   (Delta ?= (>) ->
  415.        (X = X2, $keymerge(R1,R2a,R)) ;
  416.        (X = X1, $keymerge(R1a,R2,R))
  417.   ).
  418.  
  419. $compare_keys(Delta,K1-X1,K2-X2) :- compare(Delta,K1,K2).
  420.  
  421. X^P :- call(P).
  422.  
  423. /* ------------------------------ $setof.P ------------------------------ */
  424.